
import 'dart:io';

import 'package:data_table_2/data_table_2.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/AuthUtil.dart';
import 'package:yuellyfactory/util/DialogUtil.dart';

import 'package:yuellyfactory/views/Controller/PartController.dart';
import 'package:yuellyfactory/views/base/BrandDataVC.dart';
import 'package:yuellyfactory/views/base/BrandParmVC.dart';
import 'package:yuellyfactory/views/base/EditBrandVC.dart';
import 'package:yuellyfactory/views/base/EditSerialVC.dart';
import 'package:yuellyfactory/views/base/PricePartParmVC.dart';
import 'package:yuellyfactory/views/base/PricePartRemarkVC.dart';
import 'package:yuellyfactory/views/base/SerialDataVC.dart';
import 'package:yuellyfactory/views/base/SerialParmVC.dart';
import 'package:yuellyfactory/views/dto/PricePart.dart';
import 'package:yuellyfactory/views/dto/PriceSerial.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../eventbus/EventRefreshTree.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/GlobalData.dart';
import '../../util/MathUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/Parameters.dart';
import '../dto/PriceMaterial.dart';
import '../dto/PriceParm.dart';
import 'MaterialEditVC.dart';
import 'MaterialListEditVC.dart';
import 'MaterialListParmVC.dart';
import 'MaterialRuleVC.dart';
import 'ParmVC.dart';
import 'dart:convert';
import '../dto/PriceRule.dart';
import 'MaterialAddVC.dart';

class TypeView extends StatefulWidget {
  final PartController partController;
  const TypeView({super.key, required this.partController});

  @override
  State<TypeView> createState() => _TypeViewState();
}

class _TypeViewState extends State<TypeView> {

  final formKey = GlobalKey<ShadFormState>();
  final dialogKey = GlobalKey<ShadFormState>();
  PricePart pricePart=PricePart();

  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 35; // 表头高度（含内边距）
  final double _rowHeight = 35; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距

  bool showTypeSetting=false;

  Map<String,bool> showMaps={};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();


     widget.partController.refreshPricePart=(PricePart part){
        debugPrint(part.name+"==="+part.type);
         pricePart=part;
         requestDetail();

    };
  }


  void requestDetail(){
    if(pricePart.type=='type'){
      requestType();
    }else if(pricePart.type=='serial'){
      requestSerial();
    }else if(pricePart.type=='brand'){
      requestBrand();
    }
  }
  
  void requestType(){
    BaseRequest.postHttp('price/typeinfo',parameters: {"id":pricePart.id}, canTip: false, context: context, onSuccess: (data){
      dynamic datas=data["data"];
      var part=PricePart.fromJson(datas);
      pricePart=part;
      setState(() {

      });
    }, onError: (error){});
  }

  void requestBrand(){
    BaseRequest.postHttp('price/brandinfo',parameters: {"id":pricePart.id}, canTip: false, context: context, onSuccess: (data){
      dynamic datas=data["data"];
      var part=PricePart.fromJson(datas);
      pricePart=part;
      setState(() {

      });
    }, onError: (error){});
  }
  void requestSerial(){
    BaseRequest.postHttp('price/serialinfo',parameters: {"id":pricePart.id}, canTip: false, context: context, onSuccess: (data){
      dynamic datas=data["data"];
      var part=PricePart.fromJson(datas);
      pricePart=part;
      setState(() {

      });
    }, onError: (error){});
  }




  @override
  Widget build(BuildContext context) {

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [

        if(pricePart.type=='type')
        Row(
          children: [
            Text('${pricePart.name}',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),
            SizedBox(width: ViewUtil.screenWidth(20),),
            Expanded(child: Container()),

            ShadTooltip(
              builder: (context) =>  Text(!showTypeSetting?'本类别参数配置':'隐藏'),
              child: IconButton(icon:  Icon(  showTypeSetting?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
                color:ColorUtil.colorBlue,
                iconSize: ViewUtil.screenWidth(35),onPressed: (){
                  showTypeSetting=!showTypeSetting;
                  setState(() {

                  });
                },) ,
            ),
            // IconButton(icon:  Icon(  showTypeSetting?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
            //   color:ColorUtil.colorBlue,
            //   iconSize: ViewUtil.screenWidth(35),onPressed: (){
            //     showTypeSetting=!showTypeSetting;
            //     setState(() {
            //
            //     });
            //   },),
            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Brand_Create,
                ViewUtil.addIcon('新增品牌',(){
                 // addBrand(pricePart);
                  PricePart partData=PricePart();
                  partData.parentId=pricePart.id;
                  showShadSheet(
                    side: ShadSheetSide.right,
                    context: context,
                    builder: (context) => EditBrandVC(callback: (){}, pricePart: partData)

                    ,
                  );
                })),

            // AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Type_Edit,
            //     ViewUtil.editIcon("编辑分类", (){
            //       editType();
            //     })),



          ],
        ),
        if(pricePart.type=='type')
        ViewUtil.lineView(),

        if(pricePart.type=='type')
          SizedBox(height: ViewUtil.screenHeight(2),),
        // if(pricePart.type=='type')
        //   Row(
        //     children: [
        //       ViewUtil.iconButton(Icons.settings, ColorUtil.colorBlue,  ViewUtil.screenWidth(35), (){
        //
        //       }),
        //       Expanded(child:  Container(child: const Text('分类参数设置'),)),
        //       IconButton(icon:  Icon(  showTypeSetting?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
        //         color:ColorUtil.colorBlue,
        //         iconSize: ViewUtil.screenWidth(35),onPressed: (){
        //           showTypeSetting=!showTypeSetting;
        //           setState(() {
        //
        //           });
        //         },),
        //     ],
        //   ),


        if(pricePart.type=='type'&&showTypeSetting)
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              Text('配置变动实价(材料时价，变动加工费等)',style: TextStyle(fontSize: ViewUtil.fontSize(18)),),
              SizedBox(width: ViewUtil.screenWidth(10),),
              Expanded(child: Container()),
                AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalparm_Create,
                    ViewUtil.addIcon('新增参数',(){
                      PriceParm priceParm=PriceParm();
                      priceParm.parentId=pricePart.id;
                      showShadSheet(
                        side: ShadSheetSide.right,
                        context: context,
                        builder: (context) =>  ParmVC(
                          pricePart: pricePart,
                          priceParm: priceParm,
                          callback: () {
                            //回调
                          },),
                      );
                    })),
            ],
          ),

        if(pricePart.type=='type'&&showTypeSetting)
          Container(
            height: _calculateTableHeight(pricePart.parmList.length),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
              borderRadius: BorderRadius.circular(8),
            ),
            child:  DataTable2(
                isHorizontalScrollBarVisible:true,
                columnSpacing: 12,
                //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
                minWidth: 1000,
                headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                columns: [

                  DataColumn2(
                    label: Text('参数名称'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('单位'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入方式'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('是否必填'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入数据'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('  操作'),
                    fixedWidth: 120,
                  ),

                ],
                rows: getDataRows()

            ),

          ),


        if(pricePart.type=='type'&&showTypeSetting)
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              Text('品牌概况配置',style: TextStyle(fontSize: ViewUtil.fontSize(20)),),
              SizedBox(width: ViewUtil.screenWidth(10),),
              Expanded(child: Container()),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Create, ViewUtil.addIcon('新增参数',(){
                PriceParm priceParm=PriceParm();
                priceParm.parentId=pricePart.id;
                priceParm.type=0;
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  BrandParmVC(
                    pricePart: pricePart,
                    priceParm: priceParm,
                    callback: () {
                      //回调
                    },),
                );
              })),

            ],
          ),

        if(pricePart.type=='type'&&showTypeSetting)
          Container(
            height: _calculateTableHeight(pricePart.brandParmList.length),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
              borderRadius: BorderRadius.circular(8),
            ),
            child:  DataTable2(
                isHorizontalScrollBarVisible:true,
                columnSpacing: 12,
                //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
                minWidth: 1000,
                headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                columns: [

                  DataColumn2(
                    label: Text('参数名称'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('单位'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入方式'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('是否必填'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('数据/选项'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('  操作'),
                    fixedWidth: 120,
                  ),
                ],
                rows: getBrandTableRows()

            ),

          ),



        if(pricePart.type=='type'&&showTypeSetting)
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              Text('品牌详情配置',style: TextStyle(fontSize: ViewUtil.fontSize(20)),),
              SizedBox(width: ViewUtil.screenWidth(10),),
              Expanded(child: Container()),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Create, ViewUtil.addIcon('新增参数',(){
                PriceParm priceParm=PriceParm();
                priceParm.parentId=pricePart.id;
                priceParm.type=0;
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  BrandDataVC(
                    pricePart: pricePart,
                    priceParm: priceParm,
                    callback: () {
                      //回调
                    },),
                );
              })),

            ],
          ),

        if(pricePart.type=='type'&&showTypeSetting)
          Container(
            height: _calculateTableHeight(pricePart.brandDataList.length),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
              borderRadius: BorderRadius.circular(8),
            ),
            child:  DataTable2(
                isHorizontalScrollBarVisible:true,
                columnSpacing: 12,
                //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
                minWidth: 1000,
                headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                columns: [

                  DataColumn2(
                    label: Text('参数名称'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('单位'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入方式'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('是否必填'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('数据/选项'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('  操作'),
                    fixedWidth: 120,
                  ),
                ],
                rows: getBrandDataTableRows()

            ),

          ),


        if(pricePart.type=='type'&&showTypeSetting)
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              Text('系列概况配置',style: TextStyle(fontSize: ViewUtil.fontSize(20)),),
              SizedBox(width: ViewUtil.screenWidth(10),),
              Expanded(child: Container()),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Create, ViewUtil.addIcon('新增参数',(){
                PriceParm priceParm=PriceParm();
                priceParm.parentId=pricePart.id;
                priceParm.type=0;
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  SerialParmVC(
                    pricePart: pricePart,
                    priceParm: priceParm,
                    callback: () {
                      //回调
                    },),
                );
              })),

            ],
          ),

        if(pricePart.type=='type'&&showTypeSetting)
          Container(
            height: _calculateTableHeight(pricePart.serialParmList.length),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
              borderRadius: BorderRadius.circular(8),
            ),
            child:  DataTable2(
                isHorizontalScrollBarVisible:true,
                columnSpacing: 12,
                //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
                minWidth: 1000,
                headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                columns: [

                  DataColumn2(
                    label: Text('参数名称'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('单位'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入方式'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('是否必填'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('数据/选项'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('  操作'),
                    fixedWidth: 120,
                  ),
                ],
                rows: getSerialTableRows()

            ),

          ),



        if(pricePart.type=='type'&&showTypeSetting)
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              Text('系列详情配置',style: TextStyle(fontSize: ViewUtil.fontSize(20)),),
              SizedBox(width: ViewUtil.screenWidth(10),),
              Expanded(child: Container()),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Create, ViewUtil.addIcon('新增参数',(){
                PriceParm priceParm=PriceParm();
                priceParm.parentId=pricePart.id;
                priceParm.type=0;
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  SerialDataVC(
                    pricePart: pricePart,
                    priceParm: priceParm,
                    callback: () {
                      //回调
                    },),
                );
              })),

            ],
          ),

        if(pricePart.type=='type'&&showTypeSetting)
          Container(
            height: _calculateTableHeight(pricePart.serialDataList.length),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
              borderRadius: BorderRadius.circular(8),
            ),
            child:  DataTable2(
                isHorizontalScrollBarVisible:true,
                columnSpacing: 12,
                //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
                minWidth: 1000,
                headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                columns: [

                  DataColumn2(
                    label: Text('参数名称'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('单位'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入方式'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('是否必填'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('数据/选项'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('  操作'),
                    fixedWidth: 120,
                  ),
                ],
                rows: getSerialDataTableRows()

            ),

          ),










        if(pricePart.type=='type'&&showTypeSetting)
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              Text('型号概况配置',style: TextStyle(fontSize: ViewUtil.fontSize(20)),),
              SizedBox(width: ViewUtil.screenWidth(10),),
              Expanded(child: Container()),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Partremark_Create,  ViewUtil.addIcon('新增参数',(){
                PriceParm priceParm=PriceParm();
                priceParm.parentId=pricePart.id;
                priceParm.type=0;
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  PricePartRemarkVC(
                    pricePart: pricePart,
                    priceParm: priceParm,
                    callback: () {
                      //回调
                    },),
                );
              })),

            ],
          ),

        if(pricePart.type=='type'&&showTypeSetting)
          Container(
            height: _calculateTableHeight(pricePart.remarkList.length),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
              borderRadius: BorderRadius.circular(8),
            ),
            child:  DataTable2(
                isHorizontalScrollBarVisible:true,
                columnSpacing: 12,
                //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
                minWidth: 1000,
                headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                columns: [

                  DataColumn2(
                    label: Text('参数名称'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('单位'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入方式'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('是否必填'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('数据/选项'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('  操作'),
                    fixedWidth: 120,
                  ),
                ],
                rows: getPartRemarkTableRows()

            ),

          ),

        if(pricePart.type=='type'&&showTypeSetting)
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              Text('型号详情配置',style: TextStyle(fontSize: ViewUtil.fontSize(20)),),
              SizedBox(width: ViewUtil.screenWidth(10),),
              Expanded(child: Container()),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Partparm_Create, ViewUtil.addIcon('新增参数',(){
                PriceParm priceParm=PriceParm();
                priceParm.parentId=pricePart.id;
                priceParm.type=0;
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  PricePartParmVC(
                    pricePart: pricePart,
                    priceParm: priceParm,
                    callback: () {
                      //回调
                    },),
                );
              })),

            ],
          ),

        if(pricePart.type=='type'&&showTypeSetting)
          Container(
            height: _calculateTableHeight(pricePart.partParmList.length),
            decoration: BoxDecoration(
              border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
              borderRadius: BorderRadius.circular(8),
            ),
            child:  DataTable2(
                isHorizontalScrollBarVisible:true,
                columnSpacing: 12,
                //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
                minWidth: 1000,
                headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                columns: [

                  DataColumn2(
                    label: Text('参数名称'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('单位'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('录入方式'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('是否必填'),
                    fixedWidth: 100,
                  ),
                  DataColumn2(
                    label: Text('数据/选项'),
                    size: ColumnSize.L,
                  ),
                  DataColumn2(
                    label: Text('  操作'),
                    fixedWidth: 120,
                  ),
                ],
                rows: getPartParmTableRows()

            ),

          ),



        if(pricePart.type=='type'&&showTypeSetting)
          ViewUtil.lineView(),
        if(pricePart.type=='type'&&!showTypeSetting)
          Column(
            children: brandView(),
          ),




      //TODO  新增系列录入参数定义，可录入，可选择，必填非必填。   系列参数
        // TODO  新增型号录入参数定义，可录入，可选择，必填非必填。  型号参数

        if(pricePart.type=='brand')
          Row(
            children: [
              getCrumbView(),
              SizedBox(width: ViewUtil.screenWidth(20),),
              Expanded(child:
              GestureDetector(onTap: (){

              },child: 
              Text.rich(getBrandText(pricePart),style: TextStyle(fontSize: ViewUtil.fontSize(18)),maxLines: 1,overflow: TextOverflow.ellipsis,),)

              ),

              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Serial_Create,
                  ViewUtil.addIcon("新增系列", (){
                    PricePart partData=PricePart();
                    partData.parentId=pricePart.id;
                    showShadSheet(
                      side: ShadSheetSide.right,
                      context: context,
                      builder: (context) => EditSerialVC(callback: (){}, pricePart: partData)

                      ,
                    );

                  })),
              // AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Brand_Edit,
              //     ViewUtil.editIcon("编辑品牌", (){
              //       editBrand(pricePart);
              //     })),
            ],
          ),
        if(pricePart.type=='brand')
          ViewUtil.lineView(),


        if(pricePart.type=='brand')
          Column(
            children: serialView(),
          ),


        if(pricePart.type=='serial')
          Row(

            children: [

              getCrumbView(),
              SizedBox(width: ViewUtil.screenWidth(15),),
              Expanded(child:
              GestureDetector(onTap: (){
                List<Parameters> datas=[];
                Map dataValues={};
                if(pricePart.data.isNotEmpty){
                  List list=jsonDecode(pricePart.data);
                  for(var item in list){
                    dataValues[item["name"]]=item["value"];
                  }
                }
                if(pricePart.dataDetail.isNotEmpty){
                  List list=jsonDecode(pricePart.dataDetail);
                  for(var item in list){
                    dataValues[item["name"]]=item["value"];
                  }
                }
                var text="";
                for(PriceParm parm in pricePart.serialParmList){
                  var value="--";
                  if(dataValues.containsKey(parm.id)){
                    value=dataValues[parm.id];
                  }
                  datas.add(Parameters(parm.name, value));
                  text="$text  ${parm.name}:$value";
                }
                for(PriceParm parm in pricePart.serialDataList){
                  var value="--";
                  if(dataValues.containsKey(parm.id)){
                    value=dataValues[parm.id];
                  }
                  datas.add(Parameters(parm.name, value));
                  text="$text  ${parm.name}:$value";
                }
                // datas.add(Parameters("摘要", pricePart.priceSerial.remark.toString()));
                ViewUtil.showParmSheet(context, '系列参数', datas);
              },child: Text.rich(getSerialText(pricePart),style:TextStyle(fontSize: ViewUtil.fontSize(18))),)
              ),

              SizedBox(width: ViewUtil.screenWidth(10),),

              // AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Serial_Edit,
              //     ViewUtil.editIcon('编辑系列',(){
              //       showShadSheet(
              //         side: ShadSheetSide.right,
              //         context: context,
              //         builder: (context) => EditSerialVC(callback: (){}, pricePart: pricePart)
              //
              //         ,
              //       );
              //
              //     })),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Model_Create, ViewUtil.addIcon('新增型号',(){
                addMaterial();

              }))
              ,

            ],
          ),
        if(pricePart.type=='serial')
          ViewUtil.lineView(),
        if(pricePart.type=='serial')
          Column(
            children: materialView(),
          )
      ],
    );
  }

  getCrumbName(){
   List list= ViewUtil.crumbList(pricePart.id,GlobalData.baseData);
   var name="";
   for(var i=0;i<list.length;i++){
     PricePart part=list[i];
     name=name+part.name;
     if(i!=list.length-1){
       name="$name > ";
     }
   }
   return name;
  }

  getCrumbView(){
    List<Widget> views=[];
    List list= ViewUtil.crumbList(pricePart.id,GlobalData.baseData);
    for(var i=0;i<list.length;i++){
      PricePart part=list[i];
      views.add(
          GestureDetector(onTap: (){
            eventBus.fire(EventRefreshTree(part.id));
          },child: Text(part.name,style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),));
      if(i!=list.length-1){
        views.add(Text(" > ",style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),));
      }

    }
    return Row(children: views);
  }


  TextSpan getSerialText(PricePart partData){
    
    Map dataValues={};
    List<TextSpan> list=[];
    if(partData.data.isNotEmpty){
      List list=jsonDecode(partData.data);
      for(var item in list){
        dataValues[item["name"]]=item["value"];
      }
    }
    if(partData.dataDetail.isNotEmpty){
      List list=jsonDecode(partData.dataDetail);
      for(var item in list){
        dataValues[item["name"]]=item["value"];
      }
    }
    var text="";
    for(PriceParm parm in partData.serialParmList){
      var value="--";
      bool hasAdd=false;
      if(dataValues.containsKey(parm.id)&&dataValues[parm.id].length>0){

        value=dataValues[parm.id];

        hasAdd=true;
      }
      
      text="$text  ${parm.name}:$value";
      list.add(TextSpan(
        text: "${parm.name}  ",
        style:   TextStyle(fontWeight: FontWeight.bold,color: !hasAdd&&parm.required==1?Colors.red:Colors.black),
      ));
      list.add(TextSpan(text: "$value    "));
    }

    for(PriceParm parm in partData.serialDataList){
      var value="--";
      bool hasAdd=false;
      if(dataValues.containsKey(parm.id)&&dataValues[parm.id].length>0){
        value=dataValues[parm.id];
        hasAdd=true;
      }

      text="$text  ${parm.name}:$value";
      list.add(TextSpan(
        text: "${parm.name}  ",
        style:   TextStyle(fontWeight: FontWeight.bold,color: !hasAdd&&parm.required==1?Colors.red:Colors.black),
      ));
      list.add(TextSpan(text: "$value    "));
    }
     
    // text="$text  摘要:${partData.remark}";
    
    return TextSpan(style: DefaultTextStyle.of(context).style, children: list);
  }

  List<Widget> brandView(){
    List<Widget> widgets=[];
    
    
    
    
    for(PricePart partData in pricePart.materialList){
      widgets.add(
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              GestureDetector(onTap: (){
                eventBus.fire(EventRefreshTree(partData.id));
              },child:

                Container(width: ViewUtil.screenWidth(200),
                  child: Text(' ${partData.name}',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),),
              ),

              SizedBox(width: ViewUtil.screenWidth(20),),
              Expanded(child:
              GestureDetector(onTap: (){
 
              },child: Text.rich(getBrandText(partData),style: TextStyle(fontSize: ViewUtil.fontSize(18)),maxLines: 1,overflow: TextOverflow.ellipsis,),)
              ),


              ViewUtil.editIcon("编辑品牌", (){
               // editBrand(partData);
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) => EditBrandVC(callback: (){}, pricePart: partData)

                  ,
                );



              }),

              ViewUtil.delIcon("删除品牌", (){
                showDelPart(partData);

              }),


            ],
          )
      );
    }

    return widgets;
  }


  TextSpan getBrandText(PricePart partData){

    List<TextSpan> list=[];
    Map dataValues={};
    if(partData.parmData.isNotEmpty){
      List list=jsonDecode(partData.parmData);
      for(var item in list){
        dataValues[item["name"]]=item["value"];
      }
    }
    if(partData.remarkData.isNotEmpty){
      List list=jsonDecode(partData.remarkData);
      for(var item in list){
        dataValues[item["name"]]=item["value"];
      }
    }
    var text="";
    for(PriceParm parm in partData.brandParmList){
      var value="--";
      bool hasAdd=false;
      if(dataValues.containsKey(parm.id)&&dataValues[parm.id].length>0){
        value=dataValues[parm.id];
        hasAdd=true;
      }

      text="$text  ${parm.name} $value";
      list.add(TextSpan(
        text: "${parm.name}  ",
        style:   TextStyle(fontWeight: FontWeight.bold,color: !hasAdd&&parm.required==1?Colors.red:Colors.black),
      ));
      list.add(TextSpan(text: "$value    "));
    }

    for(PriceParm parm in partData.brandDataList){
      var value="--";
      bool hasAdd=false;
      if(dataValues.containsKey(parm.id)&&dataValues[parm.id].length>0){
        value=dataValues[parm.id];
        hasAdd=true;
      }

      text="$text  ${parm.name} $value";
      list.add(TextSpan(
        text: "${parm.name}  ",
        style:   TextStyle(fontWeight: FontWeight.bold,color: !hasAdd&&parm.required==1?Colors.red:Colors.black),
      ));
      list.add(TextSpan(text: "$value    "));
    }
    

    return TextSpan(style: DefaultTextStyle.of(context).style, children: list);
  }

  List<Widget> serialView(){
    List<Widget> widgets=[];
    for(PricePart partData in pricePart.materialList){
      Map dataValues={};
      if(partData.data.isNotEmpty){
        List list=jsonDecode(partData.data);
        for(var item in list){
          dataValues[item["name"]]=item["value"];
        }
      }
      if(partData.dataDetail.isNotEmpty){
        List list=jsonDecode(partData.dataDetail);
        for(var item in list){
          dataValues[item["name"]]=item["value"];
        }
      }
      var text="";
      List<Parameters> datas=[];
      for(PriceParm parm in partData.serialParmList){
        var value="--";
        if(dataValues.containsKey(parm.id)){
          value=dataValues[parm.id];
        }
        datas.add(Parameters(parm.name, value));
        text="$text  ${parm.name}:$value";
      }

      for(PriceParm parm in partData.serialDataList){
        var value="--";
        if(dataValues.containsKey(parm.id)){
          value=dataValues[parm.id];
        }
        datas.add(Parameters(parm.name, value));
        text="$text  ${parm.name}:$value";
      }

      // datas.add(Parameters("摘要", partData.remark.toString()));
      // text="$text  摘要:${partData.remark}";
      widgets.add(
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              GestureDetector(onTap: (){
                eventBus.fire(EventRefreshTree(partData.id));
              },child: Container(width: ViewUtil.screenWidth(200),
                child: Text(' ${partData.name}',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),),
              ),

              Expanded(child:
              GestureDetector(onTap: (){

                ViewUtil.showParmSheet(context, '系列参数', datas);
              },child: Text.rich(getSerialText(partData),style: TextStyle(fontSize: ViewUtil.fontSize(18)),maxLines: 1,overflow: TextOverflow.ellipsis,),)
              ),
              ViewUtil.editIcon('编辑系列', (){
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) => EditSerialVC(callback: (){}, pricePart: partData)

                  ,
                );
              }),
              ViewUtil.delIcon("删除系列", (){
                showDelSerial(partData);
              }),


            ],
          )
      );
    }

    return widgets;
  }


  List<Widget> materialView(){
    List<Widget> widgets=[];

    for(PricePart partData in pricePart.materialList){
      widgets.add(materialItemView(partData));
    }

    return widgets;
  }



  Widget materialItemView(PricePart partData){

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            SizedBox(width: ViewUtil.screenWidth(40),),
           GestureDetector(onTap: (){
             eventBus.fire(EventRefreshTree(partData.id));
           },
            child: Container(width: ViewUtil.screenWidth(250),
                child:  Text('${partData.name}',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),)),
           ),
            SizedBox(width: ViewUtil.screenWidth(10),),


            Expanded(child: Wrap(
              crossAxisAlignment: WrapCrossAlignment.center,
              children: [
                // Container(width: ViewUtil.screenWidth(160),child: Text(
                //   '${partData.code}',
                //   style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                // ),),
                //
                // Container(width: ViewUtil.screenWidth(160),child: Text(
                //   '单价：${MathUtil.formatDouble(partData.dPrice, 2)}元',
                //   style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                // ),
                // ),



                Text.rich(
                  getPartSpec(partData),
                  style: TextStyle(fontSize: ViewUtil.fontSize(18)),
                ),


              ],
            )),


            IconButton(icon:  Icon( getIsShow(partData.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
              color:ColorUtil.colorBlue,
              iconSize: ViewUtil.screenWidth(35),onPressed: (){
                bool result= getIsShow(partData.id);
                result=!result;
                showMaps[partData.id]=result;
                setState(() {
                });
              },),

            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Model_Edit,
                ViewUtil.editIcon('编辑型号',(){

                  editMaterial(partData);
                }))
            ,
            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Model_Delete,
                ViewUtil.delIcon('删除型号',(){
                  showDelPart(partData);
                }))
            ,

          ],
        ),
        Visibility(
            visible: getIsShow(partData.id),
            child:
            Container(
              margin: EdgeInsets.only(left: ViewUtil.screenWidth(40)),
              child:Column(
                children: [

                  // Card(
                  //   color: Colors.white,
                  //   child: Column(
                  //     crossAxisAlignment: CrossAxisAlignment.start,
                  //     children: [
                  //       const SizedBox(height: 10),
                  //       Row(
                  //         children: [
                  //           SizedBox(width: ViewUtil.screenWidth(20),),
                  //           Text('型号概况',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
                  //           Expanded(child: Container()),
                  //         ],
                  //       ),
                  //       const SizedBox(height: 10),
                  //       Padding(padding: EdgeInsets.only(left: ViewUtil.screenWidth(30)),child: Wrap(
                  //         crossAxisAlignment: WrapCrossAlignment.center,
                  //         runAlignment: WrapAlignment.start,
                  //         direction: Axis.horizontal, // 水平方向排列（默认）
                  //         alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
                  //         spacing: 10, // 子组件横向间距
                  //         runSpacing: 0, // 换行后纵向间距
                  //         children: getRemarkViews(partData),
                  //       ),),
                  //
                  //       const SizedBox(height: 10),
                  //     ],
                  //   ),
                  // ),

                  // Card(
                  //   color: Colors.white,
                  //
                  //   child: Column(
                  //     crossAxisAlignment: CrossAxisAlignment.start,
                  //     children: [
                  //       const SizedBox(height: 10),
                  //       Row(
                  //         children: [
                  //           SizedBox(width: ViewUtil.screenWidth(20),),
                  //           Text('型号参数',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
                  //           Expanded(child: Container()),
                  //         ],
                  //       ),
                  //       const SizedBox(height: 10),
                  //       Padding(padding: EdgeInsets.only(left: ViewUtil.screenWidth(30)),child: Wrap(
                  //         crossAxisAlignment: WrapCrossAlignment.center,
                  //         runAlignment: WrapAlignment.start,
                  //         direction: Axis.horizontal, // 水平方向排列（默认）
                  //         alignment: WrapAlignment.start, // 水平靠左（默认值，可省略）
                  //         spacing: 10, // 子组件横向间距
                  //         runSpacing: 0, // 换行后纵向间距
                  //         children: getPartParmViews(partData),
                  //       ),),
                  //
                  //
                  //       const SizedBox(height: 10),
                  //     ],
                  //   ),
                  // ),
                  Card(
                    color: Colors.white,
                    child: Column(
                      children: [
                        const SizedBox(height: 10),
                        Row(
                          children: [
                            SizedBox(width: ViewUtil.screenWidth(20),),
                            Text('配置下级零件参数',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
                            Expanded(child: Container()),
                            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Materialparm_Edit,
                                ViewUtil.editIcon('编辑零件参数',(){
                                  showShadSheet(
                                    barrierColor: Colors.transparent,
                                    side: ShadSheetSide.right,
                                    context: context,
                                    builder: (context) =>  MaterialListParmVC(pricePart:partData , callback: () {
                                      //回调
                                    },),
                                  );
                                }))
                            ,


                          ],
                        ),
                        ViewUtil.lineView(),
                        const SizedBox(height: 10),
                        Row(
                          children: [
                            SizedBox(width: ViewUtil.screenWidth(20),),
                            Text('零件单价计算公式:',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
                            SizedBox(width: ViewUtil.screenWidth(20),),
                            Text(getRuleString(partData.materialRule),style: TextStyle(fontSize: ViewUtil.fontSize(20)),),

                            Expanded(child: Container()),
                            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Materialparm_Edit,
                                ViewUtil.editIcon('编辑公式',(){
                                  showShadSheet(
                                    barrierColor: Colors.transparent,
                                    side: ShadSheetSide.right,
                                    context: context,
                                    builder: (context) =>  MaterialRuleVC(pricePart:partData , callback: () {
                                      //回调
                                    },),
                                  );
                                }))
                            ,

                          ],
                        ),
                        ViewUtil.lineView(),
                        const SizedBox(height: 10),
                        Row(
                          children: [
                            SizedBox(width: ViewUtil.screenWidth(20),),
                            Text('零件',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
                            Expanded(child: Container()),
                            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Material_Create,
                                ViewUtil.addIcon('新增零件',(){
                              showShadSheet(
                                barrierColor: Colors.transparent,
                                side: ShadSheetSide.right,
                                context: context,
                                builder: (context) =>  MaterialListEditVC(pricePart:partData ,priceMaterial: PriceMaterial(), callback: () {
                                  //回调
                                },),
                              );
                            }))
                            ,
                            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Material_Create,
                              ViewUtil.importIcon("导入零件", (){

                                selectFileToImport(partData);
                              }),
                            )



                          ],
                        ),

                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: _outerPadding),
                          child: Container(
                            // 应用计算出的高度
                            alignment: Alignment.centerLeft,
                            height: _calculateTableHeight(partData.childMaterialList.length),
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: DataTable2(
                              columnSpacing: 12,
                              horizontalMargin: 12,
                              minWidth: 10000,
                              isHorizontalScrollBarVisible:true,
                              headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
                              dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
                              // 表头
                              columns: getTableHead(partData),
                              // 表格内容（行高固定）
                              rows: partData.childMaterialList.map((item) {
                                return DataRow(cells: getTableItem(partData,item));
                              }).toList(),
                            ),
                          ),
                        ),

                        const SizedBox(height: 10),
                      ],
                    ),
                  ),


                ],
              )),
            ),



      ],
    );
  }


  List<Widget> getRemarkViews(PricePart partData){
    List<Widget> widgets=[];
    Map remarkValues={};
    if(partData.remarkData.isNotEmpty){
      List list=jsonDecode(partData.remarkData);
      for(var item in list){
        remarkValues[item["name"]]=item["value"];
      }
    }
    for(PriceParm parm in partData.remarkList){
      List selectItems=[];
      if(parm.rule.isNotEmpty){
        List list=jsonDecode(parm!.rule);
        for (var item in list) {
          selectItems.add(item.toString());
        }
      }
      var initValue="--";
      if(remarkValues.containsKey(parm.id)){
        initValue=remarkValues[parm.id];
      }else{
        if(parm.value.isNotEmpty){
          initValue=parm.value;
        }
      }
      parm.value=initValue;
      widgets.add(
          SizedBox(width: 220,
              child:
              Row(children: [
                Text("${parm.name} ",style: TextStyle(fontSize: ViewUtil.fontSize(20)),),
                Text(initValue,style: TextStyle(fontSize: ViewUtil.fontSize(20))),
                Text(parm.unit??"",style: TextStyle(fontSize: ViewUtil.fontSize(20))),
              ],)));
    }
    return widgets;
  }


  List<Widget> getPartParmViews(PricePart partData){
    List<Widget> widgets=[];
    Map remarkValues={};
    if(partData.parmData.isNotEmpty){
      List list=jsonDecode(partData.parmData);
      for(var item in list){
        remarkValues[item["name"]]=item["value"];
      }
    }
    for(PriceParm parm in partData.partParmList){
      List selectItems=[];
      if(parm.rule.isNotEmpty){
        List list=jsonDecode(parm!.rule);
        for (var item in list) {
          selectItems.add(item.toString());
        }
      }
      var initValue="--";
      if(remarkValues.containsKey(parm.id)){
        initValue=remarkValues[parm.id];
      }else{
        if(parm.value.isNotEmpty){
          initValue=parm.value;
        }
      }
      parm.value=initValue;
      widgets.add(
          SizedBox(width: 220,
              child:
              Row(children: [
                Text("${parm.name} ",style: TextStyle(fontSize: ViewUtil.fontSize(20)),),
                Text(initValue,style: TextStyle(fontSize: ViewUtil.fontSize(20))),
                Text(parm.unit??"",style: TextStyle(fontSize: ViewUtil.fontSize(20))),
              ],)));
    }
    return widgets;
  }

  List<DataColumn2> getTableHead(PricePart partData){
    List<DataColumn2> widgets=[];
    widgets.add(const DataColumn2(
      label: Text('  操作'),
      fixedWidth: 110,
    ),);

    for(var item in partData.childParmList){
      widgets.add(DataColumn2(label: Text(item.name),fixedWidth: 100,));
    }

    return widgets;
  }

  List<DataCell> getTableItem(PricePart partData,PriceMaterial material){
    List<DataCell> widgets=[];
    widgets.add(DataCell(Row(children: [

      AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Material_Edit,
          ViewUtil.editIcon('编辑零件',(){
            showShadSheet(
              barrierColor: Colors.transparent,
              side: ShadSheetSide.right,
              context: context,
              builder: (context) =>  MaterialListEditVC(pricePart:partData ,priceMaterial: material, callback: () {
                //回调
              },),
            );

          })),
      AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Material_Delete,
          ViewUtil.delIcon('删除零件',(){
        delMaterial(material);
      }))

    ],)));

    for(var item in partData.childParmList){
      widgets.add(DataCell(Padding(
        padding: const EdgeInsets.symmetric(vertical: 0),
        child: Text(item.handle==1?
        getMaterialRuleString(item,material.data)
            :getParmValue(item.id,material.data),style: TextStyle(fontSize: ViewUtil.fontSize(18)),),
      )));
    }

    return widgets;
  }


  void delMaterial(PriceMaterial material){
    var parm={
      "id":material.id,
    };
    BaseRequest.postHttp("price/materialitemdel",parameters: parm, canTip: true, context: context, onSuccess: (data){

      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        requestDetail();
      }

    }, onError: (error){

    });
  }

  getMaterialRuleString(PriceParm parm,var data){
    if(data==null||data.length==0)return getRuleString(parm.rule);

    List datas=json.decode(data);
    String value="";
    for(var item in datas){
      if(item["id"]==parm.id){
        var handle=item["handle"];
        var v=item["rule"];
        if(handle!=null&&handle==1&&v!=null){
          if(v.contains("[")){
            value=v;
          }
        }
        break;
      }

    }



    debugPrint(parm.id+"==="+value);
    if(value.isNotEmpty){
      return getRuleString(value);
    }else{
      return getRuleString(parm.rule);
    }
  }
  getParmValue(String id,var data){
    if(data==null||data.length==0)return "";
    List datas=json.decode(data);
    var values={};
    for(var item in datas){
      values[item["id"]]=item["value"];
    }

    String value="";
    if(values.containsKey(id)){
      value=values[id].toString();
    }
    return value;
  }


  void selectFileToImport(PricePart partData)async{
    FilePickerResult? result = await FilePicker.platform.pickFiles(
    );

    if (result != null) {
      File file = File(result.files.single.path!);
      debugPrint(file.path);
      requestToUpload(file.path,partData);
    } else {
      // User canceled the picker
    }
  }

  void requestToUpload(String path,PricePart partData){
    BaseRequest.uploadToImportMaterial(path: path, partId: partData.id, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("操作成功");
        requestDetail();
      }

    }, onError: (error){});
  }

  void showDelPart(PricePart partData){
    showShadDialog(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: Text('确定要删除${partData.name}吗?'),
        description:  Padding(
          padding: const EdgeInsets.only(bottom: 8),
          child: Text(
            '点击删除将删除${partData.name}',
          ),
        ),
        actions: [
          ShadButton.outline(
            child: const Text('取消'),
            onPressed: () => Navigator.of(context).pop(false),
          ),
          ShadButton(
            child: const Text('删除'),
            onPressed: () {
              uploadDelPart(partData);

            },
          ),
        ],
      ),
    );
  }


  void showDelSerial(PricePart pricePart){
    showShadDialog(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: Text('确定要删除${pricePart.name}吗?'),
        description: const Padding(
          padding: EdgeInsets.only(bottom: 8),
          child: Text(
            '点击删除将删除系列',
          ),
        ),
        actions: [
          ShadButton.outline(
            child: const Text('取消'),
            onPressed: () => Navigator.of(context).pop(false),
          ),
          ShadButton(
            child: const Text('删除'),
            onPressed: () {
              uploadDelSerial(pricePart);

            },
          ),
        ],
      ),
    );
  }


  void uploadDelSerial(PricePart partData){
    var parm={
      "id":partData.id,

    };
    BaseRequest.postHttp("price/delpriceserial",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        Navigator.of(context).pop(false);
        eventBus.fire(EventRefreshBase());
      }
    }, onError: (error){

    });
  }




  void uploadDelPart(PricePart partData){
    var parm={
      "id":partData.id,

    };
    BaseRequest.postHttp("price/delpricemodel",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");

        Navigator.of(context).pop(false);
        eventBus.fire(EventRefreshBase());
      }
    }, onError: (error){

    });
  }
  void editMaterial(PricePart priceData){
    showShadSheet(
      side: ShadSheetSide.right,
      context: context,
      builder: (context) =>  MaterialEditVC(pricePart:priceData , callback: () {
        //回调
      },),
    );
  }



  TextSpan getPartSpec(PricePart partData){
    List<TextSpan> list=[];

    list.add(TextSpan(text: "${partData.code}    "));
    if(AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Price)){
      list.add(TextSpan(
        text: "￥ ",
        style: const TextStyle(fontWeight: FontWeight.bold),
      ));
    }

    list.add(TextSpan(text: "${MathUtil.formatDouble(partData.dPrice, 2)}    "));
    var spec=partData.spec;
   // var value="";
    if(spec.isNotEmpty){
      var  specsList=jsonDecode(spec);
      for(var i=0;i<specsList.length;i++){
         var item=specsList[i];
        // var str="${item["name"]}:${item["value"]";
        // value="$value$str";
        // if(i!=specsList.length-1){
        //   value="$value | ";
        // }
         list.add(TextSpan(
           text: "${item["name"]}  ",
           style: const TextStyle(fontWeight: FontWeight.bold),
         ));
         list.add(TextSpan(text: "${item["value"]}    "));

      }
    }

    Map remarkValues={};
    String names="";
    if(partData.remarkData.isNotEmpty){
      List list=jsonDecode(partData.remarkData);
      for(var item in list){
        remarkValues[item["name"]]=item["value"];
      }
    }
    for(PriceParm parm in partData.remarkList) {
      List selectItems = [];
      if (parm.rule.isNotEmpty) {
        List list = jsonDecode(parm!.rule);
        for (var item in list) {
          selectItems.add(item.toString());
        }
      }
      var initValue = "--";
      bool hasAdd=false;
      if (remarkValues.containsKey(parm.id)&&remarkValues[parm.id].length>0) {
        initValue = remarkValues[parm.id];
        hasAdd=true;
      } else {
        if (parm.value.isNotEmpty) {
          initValue = parm.value;
          hasAdd=true;
        }
      }
      parm.value = initValue;
      names = names + "${parm.name}:" + initValue + parm.unit + "    ";
      list.add(TextSpan(
        text: "${parm.name}  ",
        style:   TextStyle(fontWeight: FontWeight.bold,color: !hasAdd&&parm.required==1?Colors.red:Colors.black),
      ));
      list.add(TextSpan(text: "$initValue${parm.unit}    "));
    }
    //  value=value+" "+names;
    return TextSpan(style: DefaultTextStyle.of(context).style,children: list);
  }



  void editType(){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitPart(pricePart);
            },)],
            child:
            ShadForm(
              key: formKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('分类名称'),
                placeholder: const Text('请输入分类名称'),
                initialValue: pricePart.name,
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入分类名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }

  // 计算表格总高度的核心方法
  double _calculateTableHeight(int length) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }

  getDataRows(){
    List<DataRow> datas=[];
    for (var item in pricePart.parmList) {
      datas.add(DataRow(cells: [


        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.handle==0?'输入数据':'录入公式')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.handle==0?item.value:getRuleString(item.rule))),
        DataCell(
          Row(children: [
            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalparm_Edit,
              ViewUtil.editIcon('编辑参数',(){
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  ParmVC(
                    pricePart: pricePart,
                    priceParm: item,
                    callback: () {
                      //回调
                    },),
                );
              }),),
            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalparm_Edit,
              ViewUtil.delIcon('删除参数',(){
                DialogUtil.showConfimDialog(context, "删除", "确定将删除${item.name}配置", "确定", (){
                  submitDelParm(item,0);
                });
              }),)
          ],)
        ),

      ]));


    }
    return datas;
  }



  getBrandTableRows(){
    List<DataRow> datas=[];
    for (var item in pricePart.brandParmList) {
      datas.add(DataRow(cells: [

        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.type==0?'输入数据':'选择')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.type==0?item.value:getSerialSelectPart(item.rule))),
        DataCell(Row(
          children: [
            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
              ViewUtil.editIcon('编辑参数',(){
                    showShadSheet(
                    side: ShadSheetSide.right,
                    context: context,
                    builder: (context) =>  BrandParmVC(
                    pricePart: pricePart,
                    priceParm: item,
                    callback: () {
                    //回调
                    },),
                    );
              }),),
            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
             ViewUtil.delIcon("删除参数", (){
               DialogUtil.showConfimDialog(context, "删除", "确定将删除${item.name}配置", "确定", (){
                 submitDelParm(item,1);
               });
             })
            ),

          ],
        )),

      ]));

    }
    return datas;
  }


  getBrandDataTableRows(){
    List<DataRow> datas=[];
    for (var item in pricePart.brandDataList) {
      datas.add(DataRow(cells: [

        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.type==0?'输入数据':'选择')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.type==0?item.value:getSerialSelectPart(item.rule))),
        DataCell(
          Row(children: [
            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
              ViewUtil.editIcon('编辑参数',(){
                showShadSheet(
                  side: ShadSheetSide.right,
                  context: context,
                  builder: (context) =>  BrandDataVC(
                    pricePart: pricePart,
                    priceParm: item,
                    callback: () {
                      //回调
                    },),
                );
              }),
            ),
            AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
                ViewUtil.delIcon("删除参数", (){
                  DialogUtil.showConfimDialog(context, "删除", "确定将删除${item.name}配置", "确定", (){
                    submitDelParm(item,2);
                  });
                })
            ),
          ],),
        ),
      ]));

    }
    return datas;
  }


  getSerialTableRows(){
    List<DataRow> datas=[];
    for (var item in pricePart.serialParmList) {
      datas.add(DataRow(cells: [

        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.type==0?'输入数据':'选择')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.type==0?item.value:getSerialSelectPart(item.rule))),
        DataCell(
            Row(
              children: [
                AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
                  ViewUtil.editIcon('编辑参数',(){
                    showShadSheet(
                      side: ShadSheetSide.right,
                      context: context,
                      builder: (context) =>  SerialParmVC(
                        pricePart: pricePart,
                        priceParm: item,
                        callback: () {
                          //回调
                        },),
                    );
                  }),
                ),
                AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
                    ViewUtil.delIcon("删除参数", (){
                      DialogUtil.showConfimDialog(context, "删除", "确定将删除${item.name}配置", "确定", (){
                        submitDelParm(item,3);
                      });
                    })
                ),
              ],
            ),


        ),
      ]));

    }
    return datas;
  }


  getSerialDataTableRows(){
    List<DataRow> datas=[];
    for (var item in pricePart.serialDataList) {
      datas.add(DataRow(cells: [

        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.type==0?'输入数据':'选择')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.type==0?item.value:getSerialSelectPart(item.rule))),
        DataCell(
            Row(children: [
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
                ViewUtil.editIcon('编辑参数',(){
                  showShadSheet(
                    side: ShadSheetSide.right,
                    context: context,
                    builder: (context) =>  SerialDataVC(
                      pricePart: pricePart,
                      priceParm: item,
                      callback: () {
                        //回调
                      },),
                  );
                }),
              ),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
                  ViewUtil.delIcon("删除参数", (){
                    DialogUtil.showConfimDialog(context, "删除", "确定将删除${item.name}配置", "确定", (){
                      submitDelParm(item,4);
                    });
                  })
              ),


            ],),


        ),
      ]));

    }
    return datas;
  }

  getPartParmTableRows(){
    List<DataRow> datas=[];
    for (var item in pricePart.partParmList) {
      datas.add(DataRow(cells: [

        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.type==0?'输入数据':'选择')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.type==0?item.value:getSerialSelectPart(item.rule))),
        DataCell(
            Row(children: [
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Partparm_Edit,
                ViewUtil.editIcon('编辑参数',(){
                  showShadSheet(
                    side: ShadSheetSide.right,
                    context: context,
                    builder: (context) =>  PricePartParmVC(
                      pricePart: pricePart,
                      priceParm: item,
                      callback: () {
                        //回调
                      },),
                  );
                }),),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
                  ViewUtil.delIcon("删除参数", (){
                    DialogUtil.showConfimDialog(context, "删除", "确定将删除${item.name}配置", "确定", (){
                      submitDelParm(item,5);
                    });
                  })
              ),
            ],),
        ),
      ]));

    }
    return datas;
  }
  getPartRemarkTableRows(){
    List<DataRow> datas=[];
    for (var item in pricePart.remarkList) {
      datas.add(DataRow(cells: [

        DataCell(Text(item.name)),
        DataCell(Text(item.unit)),
        DataCell(Text(item.type==0?'输入数据':'选择')),
        DataCell(Text(item.required==0?'非必填':"必填")),
        DataCell(Text(item.type==0?item.value:getSerialSelectPart(item.rule))),
        DataCell(
          Row(
            children: [
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Partremark_Edit,
                ViewUtil.editIcon('编辑参数',(){
                  showShadSheet(
                    side: ShadSheetSide.right,
                    context: context,
                    builder: (context) =>  PricePartRemarkVC(
                      pricePart: pricePart,
                      priceParm: item,
                      callback: () {
                        //回调
                      },),
                  );
                }),),
              AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Globalserial_Edit,
                  ViewUtil.delIcon("删除参数", (){
                    DialogUtil.showConfimDialog(context, "删除", "确定将删除${item.name}配置", "确定", (){
                      submitDelParm(item,6);
                    });
                  })
              ),
            ],
          ),

        ),
      ]));

    }
    return datas;
  }






  getSerialSelectPart(var rule){
    if(rule.length==0)return '';
    List datas= jsonDecode(rule);
    var data="";
    for(var i=0;i<datas.length;i++){
      data=data+datas[i];
      if(i!=datas.length-1){
        data="$data,";
      }
    }
    return data;
  }
  
  getSerialRows(){
    List<DataRow> datas=[];
    for (var item in pricePart.serialList) {
      datas.add(DataRow(cells: [
        DataCell(
          ViewUtil.iconButton(Icons.note_alt_outlined, ColorUtil.colorBlue,  ViewUtil.screenWidth(35), (){

            editSerial(item);
          }),
           ),

        DataCell(Text(item.name)),
        DataCell(Text(item.name)),
        DataCell(Text(item.name)),
        DataCell(Text(item.name)),
        DataCell(Text(item.name)),
        DataCell(Text(item.name)),
        DataCell(Text(item.name)),
      ]));


    }
    return datas;
  }




  getRuleString(var rule){
    var ruleStr="";
    if(rule.isNotEmpty){
      List<dynamic> list = json.decode(rule);

      for(var item in list){
        PriceRule rule=PriceRule.fromJson(item);
        if(rule.handle==0){
          ruleStr="$ruleStr${rule.value}";
        }else{
          ruleStr="$ruleStr${rule.name}";
        }
      }
    }

    return ruleStr;
  }

  void submitPart(PricePart partData){
    if (formKey.currentState!.saveAndValidate()) {
      var values= formKey.currentState!.value;
      var name=values["name"];
      var parm={
        "name":name,
        "id":partData.id
      };
      BaseRequest.postHttp("price/editpart",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){

      });



    }
  }

  void editBrand(PricePart partData){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitPart(partData);
            },)],
            child:
            ShadForm(
              key: formKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('品牌名称'),
                placeholder: const Text('请输入品牌名称'),
                initialValue: pricePart.name,
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入品牌名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }



  void editSerial(PriceSerial serial){
    final frequency=["定频","变频"];

    List<String> fSelect=[];
    if(serial.frequency.contains("定频")){
      fSelect.add("定频");
    }
    if(serial.frequency.contains("变频")){
      fSelect.add("变频");
    }

    showShadDialog(context: context, builder: (context)=>
        ShadDialog(

            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitSerial(serial);
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child:
              Column(
                children: [
                  ShadInputFormField(
                    id: 'name',
                    initialValue: serial.name,
                    label: const Text('系列名称'),
                    placeholder: const Text('请输入系列名称'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入系列名称';
                      }
                      return null;
                    },
                  ),
                  // ShadInputFormField(
                  //   id: 'code',
                  //   initialValue: serial.code,
                  //   label: const Text('部件编码'),
                  //   placeholder: const Text('请输入部件编码'),
                  //   validator: (v) {
                  //     if (v.isEmpty) {
                  //       return '请输入部件编码';
                  //     }
                  //     return null;
                  //   },
                  // ),
                  // ShadInputFormField(
                  //   id: 'productSerial',
                  //   initialValue: serial.productSerial,
                  //   label: const Text('适用产品系列'),
                  //   placeholder: const Text('适用产品系列'),
                  //
                  // ),
                  // ShadInputFormField(
                  //   id: 'models',
                  //   initialValue: serial.models,
                  //   label: const Text('适用机型'),
                  //   placeholder: const Text('适用机型'),
                  //
                  // ),
                  // ShadInputFormField(
                  //   id: 'compressor',
                  //   initialValue: serial.compressor,
                  //   label: const Text('压缩机'),
                  //   placeholder: const Text('请输入压缩机'),
                  //
                  // ),
                  //
                  //
                  //
                  // ShadSelectMultipleFormField<String>(
                  //   id: 'frequency',
                  //   minWidth: 480,
                  //   maxWidth: 480,
                  //   label: const Text('定/变频'),
                  //   initialValue: fSelect,
                  //   options: frequency
                  //       .map((item) => ShadOption(value: item, child: Text(item)))
                  //       .toList(),
                  //
                  //   placeholder: const Text('请选择'),
                  //
                  //   validator: (v) {
                  //     if (v == null||v.isEmpty) {
                  //       return '请选择';
                  //     }
                  //     return null;
                  //   },
                  //   selectedOptionsBuilder: (context, values) =>
                  //       Text(values.map((v) => v).join(', ')),
                  //
                  //
                  // ),


                  ShadInputFormField(
                    id: 'remark',
                    initialValue: serial.remark,
                    label: const Text('摘要'),
                    placeholder: const Text('请输入摘要'),

                  ),
                ],
              ),)

        )
    );
  }

  void submitDelParm(PriceParm priceParm,int type){
    var parm={
      "type":type,
      "id":priceParm.id,
    };
    BaseRequest.postHttp("price/delpartparm",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        eventBus.fire(EventRefreshBase());
        Navigator.pop(context);

      }
    }, onError: (error){

    });
  }

  void submitSerial(PriceSerial serial){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values= dialogKey.currentState!.value;
      var name=values["name"];
      var remark=values["remark"];

      var parm={
        "name":name,
        "id":serial.id,
        "partId":pricePart.id,
        "remark":remark

      };
      BaseRequest.postHttp("price/editpartserial",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);

        }
      }, onError: (error){

      });
    }
  }


  void addMaterial(){
    PricePart partData=PricePart();
    partData.serialId=pricePart.id;
    partData.parentId=pricePart.parentId;
    partData.typeId=pricePart.typeId;
    showShadSheet(
      side: ShadSheetSide.right,
      context: context,
      builder: (context) =>  MaterialEditVC(pricePart: partData, callback: () {
        //回调

      },),
    );
  }

  void submitMaterial(){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values= dialogKey.currentState!.value;
      var name=values["name"];
      var code=values["code"];
      var spec=values["spec"];
      var parentId="";
      parentId=pricePart.id;
      var parm={
        "name":name,
        "code":code,
        "spec":spec,
        "parentId":parentId,
      };
      BaseRequest.postHttp("price/editmatterial",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("添加成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){

      });
    }
  }


  void addBrand(PricePart partData){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitBrand(partData);
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('品牌名称'),
                placeholder: const Text('请输入品牌名称'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入品牌名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }

  void submitBrand(PricePart priceData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values= dialogKey.currentState!.value;
      var name=values["name"];
      var parm={
        "name":name,
        "parentId":priceData.id
      };
      BaseRequest.postHttp("price/editpart",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("添加成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){

      });
    }
  }


  getIsShow(String id){
    bool result=false;
    if(showMaps.containsKey(id)){
      return showMaps[id];
    }
    return result;
  }


}
